<template>
  <div style="height: 10vh; background-color: #fff; padding: 10px 20px;">
    <el-card style="height: 100%;">
      <el-form :inline="true" class="searchForm">
        <el-form-item label="姓名:">
          <el-select v-model="searchForm.adminName" placeholder="请选择姓名" filterable clearable>
            <el-option v-for="user in adminData.adminNames" :key="user.value" :label="user.label" :value="user.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号:">
          <el-select v-model="searchForm.adminAccount" placeholder="请选择账号" filterable clearable>
            <el-option v-for="user in adminData.adminAccounts" :key="user.value" :label="user.label" :value="user.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号:">
          <el-select v-model="searchForm.adminPhone" placeholder="请选择手机号" filterable clearable>
            <el-option v-for="user in adminData.adminPhones" :key="user.value" :label="user.label" :value="user.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态:">
          <el-select v-model="searchForm.adminStatus" placeholder="请选择账号状态" filterable clearable>
            <el-option v-for="status in adminData.adminStatuses" :key="status.value" :label="status.label" :value="status.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="queryForm">查询</el-button>
          <el-button type="primary" @click="newDialog">新建</el-button>
          <el-button
              :disabled="selectedRows.length === 0"
              :style="{ backgroundColor: selectedRows.length === 0 ? '#ffcccc' : '#ff4d4f', color: '#fff' }"
              @click="batchDelete"
          >
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 编辑弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
    <el-form label-width="auto">
      <el-row justify="center">
        <el-col :span="20">
          <el-form-item label="姓名：" class="text-center">
            <el-input v-model="dialogForm.name" placeholder="请输入管理员姓名" class="mx-auto" style="width: 80%"/>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="账号：" class="text-center">
            <el-input v-model="dialogForm.account" placeholder="请输入管理员账号" class="mx-auto" style="width: 80%"/>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="密码：" class="text-center">
            <el-input v-model="dialogForm.passwd" placeholder="请输入管理员密码" class="mx-auto" style="width: 80%" show-password/>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="手机号：" class="text-center">
            <el-input v-model="dialogForm.phone" placeholder="请输入管理员手机号" class="mx-auto" style="width: 80%"/>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="状态：" class="text-center">
            <el-select v-model="dialogForm.status" class="mx-auto" style="width: 80%" placeholder="请选择管理员状态">
              <el-option label="启用" value="启用"/>
              <el-option label="禁用" value="禁用"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveDialog">确定</el-button>
      </el-row>
    </template>
  </el-dialog>

  <!-- 管理员列表和分页区域 -->
  <el-card style="margin: 20px; height: 70vh; display: flex; flex-direction: column;">
    <div class="table-container">
      <el-table
          :data="adminData.showList"
          border
          @selection-change="handleSelectionChange"
          ref="tableRef"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="name" label="姓名" align="center"/>
        <el-table-column prop="account" label="账号" align="center"/>
        <el-table-column prop="phone" label="手机号" align="center"/>
        <el-table-column prop="status" label="状态" align="center"/>
        <el-table-column prop="createTime" label="创建时间" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" align="center"/>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="editRow(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteRow(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
  import { onMounted, ref } from "vue";
  import { ElMessage, ElMessageBox } from 'element-plus';
  import axios from "axios";
  import { logOperation } from '@/utils/log';

  const API_URL = import.meta.env.VITE_API_BASE_URL;

  const adminData = ref({
  showList: [],
  adminNames: [],
  adminAccounts: [],
  adminPhones: [],
  adminStatuses: [
{ label: '启用', value: '启用' },
{ label: '禁用', value: '禁用' }
  ]
});

  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);

  const searchForm = ref({
  adminName: '',
  adminAccount: '',
  adminPhone: '',
  adminStatus: ''
});

  const dialogVisible = ref(false);
  const dialogTitle = ref("新建");
  const dialogForm = ref({
  id: null,
  name: '',
  account: '',
  phone: '',
  passwd: '',
  status: '启用'
});

  const selectedRows = ref([]);
  const tableRef = ref(null);

  // 查询管理员列表
  const queryForm = async () => {
  try {
  const params = {
  ...searchForm.value,
  page: currentPage.value,
  size: pageSize.value
};
  const { data } = await axios.get(`${API_URL}/v1/admin/select`, { params });
  if (data.code === 2000) {
  adminData.value.showList = data.response || [];
  total.value = data.total || 0;
  updateAdminOptions(data.response);
  ElMessage.success("数据加载成功");
} else {
  ElMessage.error("数据加载失败");
  adminData.value.showList = [];
  total.value = 0;
}
} catch (error) {
  ElMessage.error("请求异常");
  adminData.value.showList = [];
  total.value = 0;
}
};

  // 更新下拉选项
  const updateAdminOptions = (admins) => {
  const uniqueNames = new Map();
  const uniqueAccounts = new Map();
  const uniquePhones = new Map();

  (admins || []).forEach(user => {
  if (user.name) uniqueNames.set(user.name, user.name);
  if (user.account) uniqueAccounts.set(user.account, user.account);
  if (user.phone) uniquePhones.set(user.phone, user.phone);
});

  adminData.value.adminNames = Array.from(uniqueNames, ([value, label]) => ({ value, label }));
  adminData.value.adminAccounts = Array.from(uniqueAccounts, ([value, label]) => ({ value, label }));
  adminData.value.adminPhones = Array.from(uniquePhones, ([value, label]) => ({ value, label }));
};

  // 编辑管理员
  const editRow = (row) => {
  dialogTitle.value = '编辑管理员';
  dialogForm.value = { ...row, passwd: '' }; // 不加载密码
  dialogVisible.value = true;
};

  // 保存管理员信息
  const saveDialog = async () => {
  try {
  const url = dialogForm.value.id ? `${API_URL}/v1/admin/update` : `${API_URL}/v1/admin/insert`;
  const method = dialogForm.value.id ? 'put' : 'post';
  const { data } = await axios({ method, url, data: dialogForm.value });
  if (data.code === 2000) {
  ElMessage.success(dialogForm.value.id ? '更新成功' : '新建成功');
  dialogVisible.value = false;
  await queryForm();
  await logOperation('用户管理', `${dialogForm.value.id ? '更新' : '新建'}管理员 ${dialogForm.value.name}`);
} else {
  ElMessage.error(`保存失败: ${data.response?.message || '未知错误'}`);
}
} catch (error) {
  ElMessage.error('请求异常');
}
};

  // 以下方法保持不变
  const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

  const deleteAdmins = async (rows) => {
  const isBatch = Array.isArray(rows);
  const count = isBatch ? rows.length : 1;
  const ids = isBatch ? rows.map(row => row.id) : [rows];
  const confirmMessage = isBatch
  ? `您确认要删除 ${count} 个管理员吗?`
  : '您确认要删除此管理员吗?';

  try {
  await ElMessageBox.confirm(confirmMessage, '删除确认', {
  confirmButtonText: '删除',
  cancelButtonText: '取消',
  type: 'warning'
});

  const url = isBatch ? `${API_URL}/v1/admin/batchDelete` : `${API_URL}/v1/admin/delete/${ids[0]}`;
  const method = isBatch ? 'post' : 'delete';
  const requestData = isBatch ? { ids } : null;

  const { data } = await axios({
  method,
  url,
  data: requestData
});

  if (data.code === 2000) {
  ElMessage.success(isBatch ? '批量删除成功' : '删除成功');
  await queryForm();
  const logRows = isBatch ? rows : [{
  id: rows,
  name: adminData.value.showList.find(item => item.id === rows)?.name
}];
  for (const row of logRows) {
  await logOperation('用户管理', `删除管理员 ${row.name || row.id}`);
}
  if (isBatch) {
  selectedRows.value = [];
  tableRef.value.clearSelection();
}
} else {
  ElMessage.error(`删除失败: ${data.response?.message || '未知错误'}`);
}
} catch (error) {
  ElMessage.error('删除请求异常');
}
};

  const deleteRow = async (id) => {
  await deleteAdmins(id);
};

  const batchDelete = async () => {
  if (selectedRows.value.length === 0) return;
  await deleteAdmins(selectedRows.value);
};

  const resetForm = () => {
  searchForm.value = {};
  currentPage.value = 1;
  ElMessage.success("已重置筛选条件");
  queryForm();
};

  const newDialog = () => {
  dialogTitle.value = '新建';
  dialogForm.value = { status: '启用' };
  dialogVisible.value = true;
};

  const closeDialog = () => {
  ElMessageBox.confirm('您确认要关闭本弹窗吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        dialogVisible.value = false;
      })
      .catch(() => {});
};

  const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryForm();
};

  onMounted(() => {
  queryForm();
});
</script>

<style scoped>
.searchForm :deep(.el-select) {
  width: 20vh;
}

.table-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px;
}

.pagination-container {
  padding: 10px 20px;
  text-align: center;
  background-color: #fff;
  min-height: 60px;
}
</style>